var g_testcase_modify = 0;

$(document).ready(function () {
    function showProblemData(problemId) {
        g_testcase_modify = 0;
        $(".testcase-box-content").html("");
        var obj = document.getElementById('testcase-files');
        obj.outerHTML=obj.outerHTML;
        $(".problem-data-problem-id").html(problemId);
        $.getJSON("/api/admin/problem/testcases",{problemId: problemId},function(json) {
            if (json.code == 200) {
                var opt = "";
                var cases = json.data;
                opt += "Total testcase " + cases.length + ":<br>"
                opt += "<div class='probleminfo' style='margin: 0 auto;'>";
                $.each(cases, function(i, event) {
                    let num = i + 1;
                    opt += "<div class='sample-test' title='double click to modify.' case='" + cases[i].inFileName.split(".", 1) + "'>";
                    opt +=      "<span> case " + num + ":</span>" + "<span class='testcase-modify-link'>modify</span>" +
                        "<span class='testcase-delete-link'>delete</span>" +
                        "<div class='input'>" +
                        "<div class='title'>" + cases[i].inFileName + "</div>" +
                        "<div class='sample-input'>" + cases[i].inputString + "</div>" +
                        "</div>" +
                        "<div class='output'>" +
                        "<div class='title'>" + cases[i].outFileName + "</div>" +
                        "<div class='sample-output'>" + cases[i].outputString + "</div>" +
                        "</div>" +
                        "<button class='btn-testcase-save button_submit' >Save</button>" +
                        "<button class='btn-testcase-cancel button_submit' >Cancel</button>" +
                        "</div>";
                });
                opt += "</div>";
                $(".testcase-box-content").html(opt);
            }
        });
    }

    function ShowTestCaseModifyArea(element) {
        if (g_testcase_modify == 1) {
            $.messager.show('Info', "There are unsaved changes.", 5000);
            return;
        }
        g_testcase_modify = 1;

        var elementInput = element.find(".sample-input");
        var inputString = elementInput.html().replace(/<br\s*\/?>/mg,"\n");
        var elementOutput = element.find(".sample-output");
        var outputString = elementOutput.html().replace(/<br\s*\/?>/mg,"\n");
        var appendHtmlInput ="<textarea id='tempInput' class='problem-modify-textarea small-scrollbar'></textarea>"
        elementInput.text("");
        elementInput.append(appendHtmlInput);
        $("textarea#tempInput").html(inputString)
        var appendHtmlOutput ="<textarea id='tempOutput' class='problem-modify-textarea small-scrollbar'></textarea>"
        elementOutput.text("");
        elementOutput.append(appendHtmlOutput);
        $("textarea#tempOutput").html(outputString)
        $("textarea#tempInput").focus();
        $('textarea#tempOutput').autoHeight();
        $('textarea#tempInput').autoHeight();
        element.find(".btn-testcase-save").css('display','inline');
        element.find(".btn-testcase-cancel").css('display','inline');
    }

    function SaveTestCase(element) {
        var problemId = $('#problem-data-problem-id').text();
        var caseName = element.attr("case");
        var inputString = $("textarea#tempInput").val();
        var outputString = $("textarea#tempOutput").val();
        $.post("/api/admin/problem/testcases/modify",{
                problemId: problemId, caseName: caseName, inputString: inputString, outputString: outputString },
            function (data) {
                if (data.code != 200) {
                    $.messager.show('Error', data.msg, 5000);
                    $("textarea#tempInput").focus();
                    return;
                }
                $.messager.show('Info', caseName + ' updated。', 5000);
                showProblemData(problemId);
                g_testcase_modify = 0;
            },
            "json"
        );
    }

    $(".problem-data-link").click(function() {
        var scrollTop = window.pageYOffset||document.documentElement.scrollTop || document.body.scrollTop;
        var topPosInner = 60 + scrollTop;
        var leftPosIner = ($(document.body).width() - 1200)/2;
        document.getElementById('pop-inner-div-config').style.top= topPosInner +'px';
        document.getElementById('pop-inner-div-config').style.left= leftPosIner +'px';
        document.getElementById('pop-div-config').style.top= scrollTop +'px';
        document.documentElement.style.overflowY = 'hidden';

        $(".pop-div-config").fadeIn();
        $(".pop-inner-div-config").fadeIn();

        showProblemData($(this).attr("problemId"));
        return false;
    });

    $(".pop-div-config").click(function(){
        $(".pop-div-config").fadeOut();
        $(".pop-inner-div-config").fadeOut();
        document.documentElement.style.overflowY = 'scroll';
    });

    $('button.btn-testcase-upload').click(function() {
        $('#progressBarContainer').css('background-color', '#eee');
        $('#progressBar').css('width', '0%');
        $('#progressBar').text('0%');
        var problemId = $('#problem-data-problem-id').text();
        var files = document.getElementById('testcase-files').files;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var formData = new FormData();
            formData.append('problemId', problemId);
            formData.append('testcases', file, file.name);
            $.ajax({
                type: "POST",
                async: false,
                url: "/api/admin/upload/testcases",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    $('#progressBar').css('width', (i+1) * 100/files.length + '%'); // 更新宽度
                    $('#progressBar').text((i+1) * 100/files.length + '%');
                },
                error: function (data) {
                    $.messager.show('Error', "upload " + file.name + " failed.", 5000);
                }
            })
        }
        $.messager.show('Info', "upload testcase success.", 5000);
        showProblemData(problemId);
    });

    $(document).on("click",".testcase-delete-link",function(){
        var problemId = $('#problem-data-problem-id').text();
        var caseName = $(this).parent().attr("case");
        if(confirm('WARNING! Do you really want to delete this testcase?')){
        } else {
            return false;
        }
        $.post("/api/admin/problem/testcases/delete", { problemId: problemId, caseName: caseName },
            function (data) {
                if (data.code != 200) {
                    $.messager.show("Error", data.msg, 5000);
                    return;
                }
                $.messager.show('Info', "delete testcase success.", 5000);
                showProblemData(problemId);
            },
            "json"
        );
    });

    $(document).on("click",".testcase-modify-link",function() {
        var element = $(this).parent();
        ShowTestCaseModifyArea(element);
    });

    $(document).on("dblclick",".sample-test",function(){
        var element = $(this);
        ShowTestCaseModifyArea(element);
    });

    $(document).on("click",".btn-testcase-save",function() {
        var element = $(this).parent();
        SaveTestCase(element);
    });

    $(document).on("click",".btn-testcase-cancel",function() {
        var problemId = $('#problem-data-problem-id').text();
        showProblemData(problemId);
    });
})